package proxy

import (
	"com.lh.basic/config"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http/httputil"
	"net/url"
)

func Middleware(c *gin.Context, origin string) {
	target, _ := url.Parse(origin)
	proxy := httputil.NewSingleHostReverseProxy(target)
	proxy.ServeHTTP(c.Writer, c.Request)
	return
}

func Proxy(suffix string) gin.HandlerFunc {
	return func(c *gin.Context) {
		server := config.GetServe(fmt.Sprintf("server.%s", suffix)).(config.Serve)
		opts := config.GetServe(fmt.Sprintf("proxy.%s", suffix)).(config.Serve)
		if server.Port != opts.Port {
			target, _ := url.Parse(opts.Origin)
			proxy := httputil.NewSingleHostReverseProxy(target)
			proxy.ServeHTTP(c.Writer, c.Request)
		} else {
			c.Next()
		}
	}
}
